// pages/manhua/detail.js
// 在页面中定义激励视频广告
let videoAd = null
Page({

    /**
     * 页面的初始数据
     */
    data: {
        background: {
            'background-image': 'linear-gradient(45deg, #fc587d,#f96770)'
        },
        buttonCustomStyle: {
            'background-color': '#fc587d'
        },
        noticeList: [
            '左右拖动按钮可以看效果'
        ],
        data: {},
        options: '',

        isShowSelect: false,
        selectText: '可选',
        selectList: [],

        phone_height: 657,
        height: 500,
        width: 750,

        // 生成后的图片
        image: '',
        // 上传的图片地址 
        uploadImage: '',
        beforeImageUrl: '',
        afterImageUrl: '',
        saveImageUrl: "",
        wrapper: false,
        cartoon_type: "tccartoon", //动漫风格 tccartoon默认
        Action: "JPCartoon",
        type: ""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this;

        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('acceptDataFromOpenerPage', function(data) {
            console.log(data)
            that.setData({
                data: data,
                beforeImageUrl: data.before_img,
                afterImageUrl: data.after_img,
                cartoon_type: data.cartoon_type || "",
                Action: data.Action || "",
                type: data.type || ""
            })

            // 处理下options
            if (data['options'] && data['options'].length > 0) {
                that.data.selectList = [];
                that.data.selectText = data['options'][0]['name'];
                that.data.options = data['options'][0]['value'];

                data['options'].map((val, idx) => {
                    that.data.selectList.push({
                        label: val.name,
                        value: val.value
                    })
                })
            }
        });

        // 在页面onLoad回调事件中创建激励视频广告实例
if (wx.createRewardedVideoAd) {
  videoAd = wx.createRewardedVideoAd({
    adUnitId: 'adunit-231a7a7ed5bb7f19'
  })
  videoAd.onLoad(() => {})
  videoAd.onError((err) => {})
  videoAd.onClose((res) => {})
}




videoAd.onClose(res => {
  // 用户点击了【关闭广告】按钮
  if (res && res.isEnded) {
    // 正常播放结束，可以下发游戏奖励

    this.saveImageToPhotosAlbum()
  } else {
    wx.showToast({
      title: '未播放完,不能保存照片哦~',
      icon:"none"
    })
  }
})

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },
    saveFunc(){
       // 用户触发广告后，显示激励视频广告
       if (videoAd) {
        wx.showModal({
          title: '提示',
          content: '需要观看视频才能保存哦',
          success (res) {
            if (res.confirm) {
              videoAd.show().catch(() => {
                // 失败重试
                videoAd.load()
                  .then(() => videoAd.show())
                  .catch(err => {
                    console.log('激励视频 广告显示失败')
                  })
              })
            } else if (res.cancel) {
             

            }
          }
        })

      
      }else{
        this.saveImageToPhotosAlbum()
      }
    },
    saveImageToPhotosAlbum() {
     
        let base64 = this.data.saveImageUrl
        let timer = new Date().getTime();

                       
        let filePath = wx.env.USER_DATA_PATH + '/' + timer + '.png';               
        wx.getFileSystemManager().writeFile({                   
            filePath: filePath,
              //创建一个临时文件名
                               data: base64,
                //写入的文本或二进制数据
                               encoding: 'base64',
              //写入当前文件的字符编码
                               success: res => {                        wx.saveImageToPhotosAlbum({                            filePath: filePath,                            success: function(res2) {                                wx.showToast({                                    title: '保存成功，请从相册选择再分享',                                    icon: "none",                                    duration: 5000                                })                            },                            fail: function(err) {                                wx.showToast({                                    title: '保存失败',                                    icon: "none",                                    duration: 5000                                })                            }                        })                    },
                               fail: err => {
                wx.showToast({                                    title: '保存失败',                                    icon: "none",                                    duration: 5000                                })                   
            }               
        })



                   
    },
    chooseImage() {
        let that = this;

        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'],
            success: function(res) {
                let tempImagePath = res.tempFilePaths[0];

                // 清空之前选择的图片
                that.initImg();

                // 上传并检测图片合法性
                // #ifndef H5
                wx.compressImage({
                        src: tempImagePath,
                        quality: 80,
                        success: res1 => {
                            // 如果路径最后一位是.，则不上传压缩路径。
                            let uploadPath = res1.tempFilePath;
                            if (uploadPath.substr(uploadPath.length - 1, 1) == '.') {
                                uploadPath = tempImagePath;
                            }

                            that.uploadImg(uploadPath);
                        }
                    })
                    // #endif
                    // #ifdef H5
                that.uploadImg(tempImagePath);
                // #endif
            }
        });
    },

    uploadImg(path) {
        let that = this;

        wx.getImageInfo({
            src: path,
            success: function(image) {

                // 竖图且大于屏幕70%，将高度直接减半显示
                if (image.height > image.width && image.height > that.data.phone_height * 0.7) {
                    that.setData({
                        height: image.height * 0.6
                    })
                } else {
                    that.setData({
                        height: image.height / (image.width / that.data.width)
                    })
                }
                that.turnBase64IdCard(path)
            }
        });

        that.setData({
            beforeImageUrl: path,
            wrapper: true
        })
    },
    turnBase64IdCard(file) {

        let that = this;

        wx.getFileSystemManager().readFile({
                filePath: file,
                encoding: 'base64',
                success: res => {
                    that.getImage(res.data)

                }
            })
            // #endif
    },
    //任务漫画处理
    getImage(image_base64) {
        let that = this;
        wx.request({
            url: "https://www.volcengine.com/api/exp/2/vloc-ai",
            method: "POST",
            data: {
                ServiceName: "cv",
                Action: that.data.Action,
                Version: "2020-08-26",
                cartoon_type: that.data.cartoon_type, //tccartoon 萌漫风  classic_cartoon 复古风 hkcartoon全图港漫风 jpcartoon全图日漫风 jpcartoon_head人像日漫风
                image_base64: image_base64,
                rotation: 0, //允许旋转0 不允许1
                type: that.data.type

            },
            success(res) {
                if (res.statusCode == 200) { //图片转码成功
                    let { Result } = res.data
                    if (Result.code == 10000) {
                        let { image } = Result.data;
                        that.setData({
                            afterImageUrl: "data:image/jpg;base64," + image,
                            saveImageUrl: image,
                            wrapper: false,
                        })
                    } else {
                        that.setData({
                            wrapper: false,
                        })
                        wx.showToast({
                            title: "处理失败",
                            icon: 'none'
                        })
                    }
                } else {
                    that.setData({
                        wrapper: false,
                    })
                    wx.showToast({
                        title: "处理失败",
                        icon: 'none'
                    })
                }

            }
        })
    },
    showSelect() {
        this.data.isShowSelect = true;
    },
    selectConfirm(e) {
        this.data.selectText = e[0]['label'];
        this.data.options = e[0]['value'];
    },
    initImg() {
        let that = this;
        that.setData({
            afterImageUrl: that.data.after_img,
            beforeImageUrl: that.data.before_img,
            image: "",
            uploadImage: ""
        })
    },
    saveImg() {
        let that = this;
        wx.getImageInfo({
            src: that.image,
            success: function(image) {
                wx.saveImageToPhotosAlbum({
                    filePath: image.path,
                    success: function() {
                        that.globalUtil.utilAlert('图片保存成功');
                    },
                    fail(e) {}
                });
            }
        });
    },

    previewImage() {
        let that = this;
        wx.previewImage({
            urls: [that.data.image],
            longPressActions: {
                itemList: ['发送给朋友', '保存图片', '收藏'],
                success: function(data) {
                    console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
                },
                fail: function(err) {
                    console.log(err.errMsg);
                }
            }
        });
    },
    getSuffix(url) {
        return url.substring(url.lastIndexOf('.') + 1, url.length);
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})